#include "stdafx.h"
#include "SOCK_Acceptor.h"

#pragma comment(lib,"ws2_32.lib") // winsock library

// Initialize a passive-mode acceptor socket.
SOCK_Acceptor::SOCK_Acceptor() 
{
	WSADATA wsa;

	WSAStartup(MAKEWORD(2,2), &wsa);
};

SOCK_Acceptor::~SOCK_Acceptor()
{
	::closesocket(handle_);
}

char* SOCK_Acceptor::myIp()
{
    char ac[80];
	gethostname(ac, sizeof(ac));
    struct hostent *phe = gethostbyname(ac);
    
	struct in_addr addr;
    memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
    return inet_ntoa(addr);
}

// A second method to initialize a passivemode
// acceptor socket, analogously to the constructor.
bool SOCK_Acceptor::open(const INET_Addr &sock_addr)
{ 
	// Create a local endpoint of communication.
	handle_ = socket(AF_INET, SOCK_STREAM, 0);
	if(INVALID_SOCKET == handle_)
		return false;

	// Associate address with endpoint.
	if (-1 == bind(handle_, sock_addr.addr (), sock_addr.size()))
		return false;

	// Make endpoint listen for connections.
	if(-1 == listen(handle_, 5))										//Maximum 5 pending connections. Starts listening for incomming connections. Blocking call.
			return false;

	return true;
};

// Accept a connection and initialize the <stream>.
void SOCK_Acceptor::accept(SOCK_Stream &s) 
{
	s.set_handle(::accept(handle_, 0, 0));
}

SOCKET SOCK_Acceptor::getHandle()
{
	return handle_;
}
